package com.iotechn.unimall.app.config.ezviz;

import com.alibaba.fastjson.JSONObject;
import com.iotechn.unimall.data.component.CacheComponent;
import lombok.Data;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

/**
 * Created by rize on 2019/6/9.
 */
@Data
@Configuration
@ConfigurationProperties(prefix = "com.iotechn.unimall.ezviz")
public class EzvizService {

    private String appKey;
    private String appSecret;
    private String ezvizUrl;



    private static final MediaType CONTENT_TYPE = MediaType.parse("application/x-www-form-urlencoded");
    private static final Logger LOGGER = LoggerFactory.getLogger(EzvizService.class);
    public static final String ACCESS_TOKEN = "EZVIZ_ACCESS_TOKEN";
    private static final int DAY = 7;

    @Autowired
    private CacheComponent cacheComponent;

    @PostConstruct
    public void init() {
        if(StringUtils.isNotBlank(cacheComponent.getRaw(ACCESS_TOKEN)))
            return;

        OkHttpClient mOkHttpClient = new OkHttpClient();
        StringBuilder sb = new StringBuilder()
                .append("appKey=").append(appKey)
                .append("&")
                .append("appSecret=").append(appSecret);
        RequestBody body = RequestBody.create(CONTENT_TYPE, sb.toString());
        Request request = new Request.Builder().url(ezvizUrl).post(body).build();
        try {
            Response response = mOkHttpClient.newCall(request).execute();
            JSONObject result = JSONObject.parseObject(response.body().string());
            String code = result.get("code").toString();
            // 获取成功
            if ("200".equals(code)) {
                JSONObject data = JSONObject.parseObject(result.get("data").toString());
                long seconds = TimeUnit.DAYS.toSeconds(DAY);
                // 提前30分钟过期
                cacheComponent.putRaw(ACCESS_TOKEN, data.get("accessToken").toString(), (int) (seconds - TimeUnit.MINUTES.toSeconds(30)));
            } else
                LOGGER.warn("萤石TOKEN获取失败：{}", result.get("msg").toString());
        }catch (Exception e){
            LOGGER.warn("萤石TOKEN获取失败：{}", e.getMessage());
        }
    }

    public void refresh(){
        init();
    }

}
